package com.example.pdfprocessor.controller;

import com.example.pdfprocessor.service.PdfService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

@Controller
@RequiredArgsConstructor
@Slf4j
public class PdfController {

    private final PdfService pdfService;

    @GetMapping("/")
    public String index() {
        return "index";
    }

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file,
                                  RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "请选择文件上传");
            return "redirect:/";
        }

        try {
            // 检查文件是否为PDF
            String contentType = file.getContentType();
            log.info("上传文件类型: {}, 文件名: {}, 大小: {}", contentType, file.getOriginalFilename(), file.getSize());
            
            if (contentType == null || !contentType.equals("application/pdf")) {
                redirectAttributes.addFlashAttribute("message", "只支持PDF文件格式");
                return "redirect:/";
            }

            String filename = pdfService.processAndSavePdf(file);
            redirectAttributes.addFlashAttribute("filename", filename);
            redirectAttributes.addFlashAttribute("message", "文件处理成功");
            return "redirect:/preview?filename=" + filename;
        } catch (IOException e) {
            log.error("文件处理失败", e);
            // 生成用户友好的错误消息
            String errorMsg = "文件处理失败";
            if (e.getMessage().contains("No PDFHeader")) {
                errorMsg = "文件格式错误，不是有效的PDF文件";
            } else if (e instanceof FileNotFoundException || e.getMessage().contains("系统找不到指定的路径")) {
                errorMsg = "文件存储路径错误，请联系管理员检查系统配置";
            } else {
                errorMsg = "文件处理失败: " + e.getMessage();
            }
            redirectAttributes.addFlashAttribute("message", errorMsg);
            return "redirect:/";
        } catch (Exception e) {
            log.error("发生未知错误", e);
            redirectAttributes.addFlashAttribute("message", "处理过程中发生错误: " + e.getMessage());
            return "redirect:/";
        }
    }

    @GetMapping("/preview")
    public String previewPage(@RequestParam("filename") String filename, Model model) {
        File file = pdfService.getPdfFile(filename);
        if (!file.exists()) {
            model.addAttribute("errorMessage", "找不到文件，可能已被删除");
            return "error";
        }
        model.addAttribute("filename", filename);
        return "preview";
    }

    @GetMapping("/view/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {
        File file = pdfService.getPdfFile(filename);
        if (!file.exists()) {
            return ResponseEntity.notFound().build();
        }
        
        Resource resource = new FileSystemResource(file);

        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_PDF)
                .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"")
                .body(resource);
    }

    @GetMapping("/download/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
        File file = pdfService.getPdfFile(filename);
        if (!file.exists()) {
            return ResponseEntity.notFound().build();
        }
        
        Resource resource = new FileSystemResource(file);

        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_PDF)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
                .body(resource);
    }
} 